package com.googlecode.perfectable.persistable.serialization;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import javax.annotation.Nullable;

import com.googlecode.perfectable.persistable.session.Identifier;
import com.googlecode.perfectable.persistable.storage.Persister;

public class PersistanceOutputStream extends ObjectOutputStream {
	private final Separator separator;
	private final Persister persister;
	private final Object solid;

	public PersistanceOutputStream(OutputStream sink, Persister persister, Separator separator, Object solid)
			throws IOException {
		super(sink);
		this.separator = separator;
		this.persister = persister;
		this.solid = solid;
		this.enableReplaceObject(true);
	}

	@Override
	@Nullable
	protected Object replaceObject(@Nullable Object obj) throws IOException {
		if(obj != null && obj != this.solid && this.separator.isSeparate(obj))
		{
			final Identifier<Object> identity = this.persister.persist(obj);
			return identity;
		}
		return super.replaceObject(obj);
	}
}
